<?php
//定时检测积分过期
namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;


class IntegraCheck extends Command
{
    protected function configure()
    {
        $this->setName('integra_check');
    }

    protected function execute(Input $input, Output $output)
    {

        $user = db('integral_change_log')->field('user_id')->where('user_del','0')->group('user_id')->select();
        foreach ($user AS $key => $value) {
            $thisDay = date('Y-m-d H:i:s');
            $userId = $value['user_id'];
            
            //过期积分
            $expireScore = db('integral_change_log')
                ->where(['user_id'=>$userId,'type'=>'2','status'=>'0','user_del'=>'0'])
                ->where('exptime','<=',$thisDay)
                ->sum('residue_score');
            if ($expireScore > 0) {
                Db::startTrans();
                try{
                    $user11 = db('user')->where('id',$userId)->find();
                    if (!empty($user11)) {
                        $user = db('user')->where('id',$userId)->lock(true)->find();
                        db('user')->where('id',$userId)->setDec('integral',$expireScore);
                        //更新过期积分记录状态
                        db('integral_change_log')
                            ->where(['user_id'=>$userId,'type'=>'2','status'=>'0','user_del'=>'0'])
                            ->where('exptime','<=',$thisDay)
                            ->update([
                                'status'=>1,
                                'residue_score'=>0
                            ]);

                        //新增过期积分的记录
                        db('integral_change_log')->insert([
                            'user_id'=>$userId,
                            'store_id'=>$user['store_id'],
                            'scene'=>6,
                            'score'=>$expireScore,
                            'total_score'=>$user['integral']-$expireScore,
                            'type'=>3,
                            'addtime'=>$thisDay,
                        ]);
                        Db::commit();
                    }
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
        }
        exit('更新过期积分脚本执行完成');
    }
}
